package com.example.rtmppusher.util;

import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

public class Utils {

    protected static Toast toast;

    //弹窗
    public static void alert(Activity activity, String message) {
        if (toast != null) toast.cancel();
        toast = Toast.makeText(activity, message, Toast.LENGTH_SHORT);
        toast.show();
    }

    //显示控件
    public static void show(View view) {
        view.post(() -> {
            view.setVisibility(View.VISIBLE);
        });
    }

    //隐藏控件
    public static void hide(View view) {
        view.post(() -> {
            view.setVisibility(View.GONE);
        });
    }

    //限制用户频繁点击
    public static void limitEventFrequency(View view) {
        view.setEnabled(false);
        if (view instanceof ViewGroup) {
            ViewGroup viewGroup = (ViewGroup) view;
            int count = viewGroup.getChildCount();
            for (int i = 0; i < count; i++) {
                View child = viewGroup.getChildAt(i);
                child.setEnabled(false);
            }
        }
        view.postDelayed(() -> {
            unlimitEventFrequency(view);
        }, 500);
    }

    //解除频繁点击限制
    public static void unlimitEventFrequency(View view) {
        view.setEnabled(true);
        if (view instanceof ViewGroup) {
            ViewGroup viewGroup = (ViewGroup) view;
            int count = viewGroup.getChildCount();
            for (int i = 0; i < count; i++) {
                View child = viewGroup.getChildAt(i);
                child.setEnabled(true);
            }
        }
    }

    //线程休眠
    public static void sleep(long ms) {
        try {
            Thread.sleep(ms);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
